import { http } from "@/utils/http";
import { baseUrlApi } from "./utils";
import { storageLocal } from "@pureadmin/utils";
import type { DataInfo } from "@/utils/auth";

type Result = {
  success: boolean;
  data: Array<any>;
};

export const getAsyncRoutes = () => {
  return http.request<Result>("get", baseUrlApi("getmenus/")).then(res => {
    const userKey = "user-info";
    const username =
      storageLocal().getItem<DataInfo<number>>(userKey)?.username ?? "";

    const addUsernameToFrameSrc = (routes: any[]) => {
      routes.forEach(route => {
        if (route.children) {
          route.children.forEach((child: any) => {
            if (child.meta?.frameSrc) {
              child.meta.frameSrc = `${child.meta.frameSrc}&per_account=${username}`;
            }
          });
        }
      });
      return routes;
    };

    return {
      ...res,
      data: addUsernameToFrameSrc(res.data)
    };
  });
};
